import 'package:flutter/cupertino.dart';
import 'package:xindong/routes/tab_moments/model/xindong_dongtai_class.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/widgets/video/xindong_common_video_list_ctr.dart';
import 'package:xindong/widgets/video/xindong_common_video_player_container.dart';

class XinDongDongTaiVideoView extends StatefulWidget {
  final XinDongDongTaiClass model;
  final BuildContext cellContext; // 取单元格上下文，才能匹配合适的高度
  final bool isDetails;
  final bool isSpace;

  const XinDongDongTaiVideoView(
      {super.key, required this.model, required this.cellContext, this.isDetails = false, this.isSpace = false});

  @override
  State<XinDongDongTaiVideoView> createState() => _XinDongDongTaiVideoViewState();
}

class _XinDongDongTaiVideoViewState extends State<XinDongDongTaiVideoView> {
  final _videoController = XinDongCommonVideoListCtr.to;
  late String _videoKey;
  late double _aspectRatio;

  @override
  void initState() {
    super.initState();

    _aspectRatio = ImageUtil.imageSizeAspectRatioFromUrl(
      imageUrl: widget.model.video,
      start: "size:",
      end: ":size",
      defaultScale: 168 / 224,
    );
    // 视频的Key（自定义生成）
    _videoKey = _videoController.generateMomentKey(
      did: widget.model.dy_id,
      isDetails: widget.isDetails,
      isSpace: widget.isSpace,
    );
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (!mounted) return;

      // 如果为空，第一个视频key设为默认videoKey
      if (_videoController.videoPlayingKeys.isEmpty) {
        _videoController.videoPlayingKeys.add(_videoKey);
      }
      // 添加Key上下文
      _videoController.addContext(videoKey: _videoKey, context: widget.cellContext);
    });
  }

  @override
  void dispose() {
    // 移除Key上下文
    _videoController.removeContext(videoKey: _videoKey);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: _aspectRatio > 1.0 ? 198 : 158,
      child: XinDongCommonListVideoWidget(
        videoKey: _videoKey,
        cover: widget.model.cover,
        videoUrl: widget.model.video,
        aspectRatio: _aspectRatio,
      ),
    );
  }
}
